import { useState } from 'react'

type Props = {
  onAddTodo: (text: string) => void
}

const TodoAdd = ({ onAddTodo }: Props) => {
  const [value, setValue] = useState('')

  const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value)
  }

  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.code === 'Enter') {
      if (value.trim().length === 0) return

      onAddTodo(value)

      // 清空内容
      setValue('')
    }
  }

  return (
    <header className='header'>
      <h1>todos</h1>
      <input
        className='new-todo'
        placeholder='What needs to be done?'
        autoFocus
        value={value}
        onChange={onChange}
        onKeyDown={onKeyDown}
      />
    </header>
  )
}

export default TodoAdd
